import { DataSource, DataSourceOptions } from "typeorm";
import * as fs from "fs";
import * as path from "path";
import { entities } from "./entities";

const { ACTIVE } = process.env;

const tidb: DataSourceOptions = {
    type: "mysql",
    host: process.env.TIDB_HOST,
    port: Number(process.env.TIDB_PORT),
    username: process.env.TIDB_USER,
    password: process.env.TIDB_PASSWORD,
    database: process.env.TIDB_DATABASE,
    ssl: {
        ca: fs.readFileSync(
            path.join(process.cwd(), `${process.env.TIDB_CA_PATH}`)
        ),
    },
    entities,
    synchronize: true,
    logging: true
};

const mysql: DataSourceOptions = {
    type: "mysql",
    host: process.env.MYSQL_HOST,
    port: Number(process.env.MYSQL_PORT),
    username: process.env.MYSQL_USER,
    password: process.env.MYSQL_PASSWORD,
    database: process.env.MYSQL_DATABASE,
    entities,
    synchronize: true,
    logging: true
};

const db = ACTIVE == "dev" ? tidb : ACTIVE == "pro" ? mysql : tidb;

export const AppDataSource = new DataSource(db);
